<?php

class Orderedcategories_model extends CI_Model {
	
	private $orderedCategories = array();
	
	private $unsortedCategory;
	
	function __construct() {
        $sql = "SELECT * FROM `categories` \n"
		    . "order by category_id ASC\n";
    		
        $query = $this->db->query($sql);
        
        $prev_cat = null;
        
        foreach ($query->result() as $row)
		{
			$category = new Category();
			$category->category_id = $row->category_id;
			$category->name = $row->name;
			$category->order = $row->order;
			
			if($category->category_id == "0")
			{
				$this->unsortedCategory = $category;
			} else {				
				$this->orderedCategories[$category->category_id] = $category;
			}
		}
    }
    
    public function getUnsortedCategory()
    {
    	return $this->unsortedCategory;
    }
    
	public function addCategory($category_id, $name)
    {
    	$firstIndex = substr($category_id, 0, -2)."10";
    	if(isset($this->orderedCategories[$category_id])) {
    		$order = $this->orderedCategories[$category_id]->order;
    	} else {
    		$order = 0;
    	}
    	
    	while(isset($this->orderedCategories[$firstIndex])) {
    		$firstIndex++;	
    	}
    	
    	$newCategory = new Category();
    	$newCategory->category_id = $firstIndex;
		$newCategory->name = $name;
		$newCategory->order = $order;
    	
		foreach ($this->orderedCategories as $category) 
		{
			if(strlen($category->category_id) == strlen($firstIndex))
			{
				if($category->order >= $order)
				{
					$category->order++;
					$category->update();
				}
			}
		}
		
		$this->orderedCategories[$firstIndex] = $newCategory;
		$newCategory->upload();
		
		usort($this->orderedCategories, array($this,"orderSort"));
    }
    
	public function editCategory($category_id, $name)
    {
    	//KLogger::Instance()->LogDebug("Changeing id: " . $this->orderedCategories[$category_id]->category_id . " name: " . $this->orderedCategories[$category_id]->name);
    	//KLogger::Instance()->LogDebug("To id: " . $category_id . " name: " . $name);
    	$this->orderedCategories[$category_id]->name = $name;
    	$this->orderedCategories[$category_id]->update(); 
    	
    	usort($this->orderedCategories, array($this,"orderSort"));
    }
    
	public function moveCategoryDown($category_id) 
    { 
    	$category = $this->orderedCategories[$category_id];

    	foreach($this->orderedCategories as $cat)
    	{
    		if($this->hasSameParent($cat->category_id, $category_id) && $cat->order == $category->order + 1)
    		{
    			KLogger::Instance()->LogDebug("Move down clicked cat: " . $category->name . " , " .  $category->order . " changing with: " . $cat->name . " , " . $cat->order);
    			
    			$cat->order = $cat->order - 1;
    			$cat->update();

    			$category->order = $category->order + 1;
		    	$category->update();
		    	
    			break; 
    		}
    	}
    	usort($this->orderedCategories, array($this,"orderSort"));
    }
    
    public function moveCategoryUp($category_id) 
    {  	
    	$category = $this->orderedCategories[$category_id];

    	foreach($this->orderedCategories as $cat)
    	{
    		if($this->hasSameParent($cat->category_id, $category_id) && $cat->order == $category->order - 1)
    		{
    			$cat->order = $cat->order + 1;
    			$cat->update();
    			
    			$category->order = $category->order - 1;
		    	$category->update();
		    	
    			break; 
    		}
    	}
    	usort($this->orderedCategories, array($this,"orderSort"));
    }
    
    public function removeCategory($id) {
    	$childrens = $this->childrens($this->orderedCategories[$id]);
    	
    	foreach($childrens as $child) 
		{
			$child->delete();
    		unset($this->orderedCategories[$child->category_id]);
		}
    	
    	$this->orderedCategories[$id]->delete();
    	unset($this->orderedCategories[$id]);    	
    }
    
	public function childrens($parent) {
		$result = array();
		$allCategoires = $this->orderedCategories;
		
		foreach($allCategoires as $item) 
		{
			if(strlen($parent->category_id) + 2 == strlen($item->category_id) && substr($item->category_id, 0, strlen($parent->category_id)) == $parent->category_id) {
				array_push($result, $item);
			}
		}
		return $result;
	}
	
	public function rootCategories() {
		$result = array();
		$categoires = $this->orderedCategories;
		
		foreach($categoires as $item) 
		{
			if(strlen($item->category_id) == 2) {
				array_push($result, $item);
			}
		}
		return $result;
	}
	
	public function getAllCategories() 
	{
		return $this->orderedCategories;
	}
    
 	public function orderSort($a, $b) 
    {
    	if ($a->category_id == $b->category_id || strlen($a->category_id) == strlen($b->category_id)) {
    		return($a->order < $b->order) ? -1 : 1;
    	} else return($a->category_id < $b->category_id ) ? -1 : 1; 
    }
    
    public function getFirstCategoryName()
    {
    	usort($this->orderedCategories, array($this,"orderSort"));
    	return current($this->orderedCategories)->name;
    }
    
	public function render()
	{
		usort($this->orderedCategories, array($this,"orderSort"));
    	$res = array();
    	foreach ($this->orderedCategories as $category)
    	{
    		array_push($res, json_encode($category));
    	}
    	return $res;
	}
    
	private function hasSameParent($id_1, $id_2) {
		if(strlen($id_1) == strlen($id_2) && substr($id_1, 0, -2) == substr($id_2, 0, -2) )
		{
			return true;
		}
		
		return false;
	}
	
    /*
    public function getCategoryName($id)
    {
    	if(!isset($this->orderedCategories[$id])) {
    		if($id."" == "0") return "Kategorizálatlan";
    		else return "";
    	} else {    		
    		return $this->orderedCategories[$id]->name;
    	} 
    }
    
    public function getFirstCategoryName()
    {
    	if(!isset($this->orderedCategories[10])) {
    		return "";
    	} else return $this->orderedCategories[10]->name;
    }
    
    public function addCategory($category_id, $name)
    {
   	 	if(isset($this->orderedCategories[$category_id]))
    	{
    		$newArray = array();
	    	$length = strlen($category_id);
	    	
	    	foreach($this->orderedCategories as $category) 
	    	{    		
	    		if($length <= strlen($category->category_id) ) 
	    		{
	    			$prefix = substr($category->category_id, 0, $length);
	    			$sufix = substr($category->category_id, $length);
	    			
	    			if($prefix >= $category_id) 
	    			{	    				
	    				$prefix = $prefix+1;
	    			
		    			$category->category_id = $prefix . $sufix;
		    			$newArray[$category->category_id] = $category;
		    			$category->update();
	    			} else {
	    				$newArray[$category->category_id] = $category;
	    			}
	    		} else {
	    			$newArray[$category->category_id] = $category;
	    		}
	    	}
	    	
	    	$newArray[$category_id] = new Category();
	    	$newArray[$category_id]->name = $name;
	    	$newArray[$category_id]->category_id = $category_id;
	    	$newArray[$category_id]->upload();
	    	
	    	$this->orderedCategories = $newArray;
	    	
	    	$this->render();
    	} else {
    		$this->orderedCategories[$category_id] = new Category();
	    	$this->orderedCategories[$category_id]->name = $name;
	    	$this->orderedCategories[$category_id]->category_id = $category_id;
	    	$this->orderedCategories[$category_id]->upload();
	    	
	    	$this->render();
    	}
    }
    
    public function editCategory($category_id, $name)
    {
    	KLogger::Instance()->LogDebug("Changeing id: " . $this->orderedCategories[$category_id]->category_id . " name: " . $this->orderedCategories[$category_id]->name);
    	KLogger::Instance()->LogDebug("To id: " . $category_id . " name: " . $name);
    	$this->orderedCategories[$category_id]->name = $name;
    	$this->orderedCategories[$category_id]->update(); 
    	
    	$this->render();
    }
	
    public function removeCategory($category_id)
    {
    	if(isset($this->orderedCategories[$category_id]))
    	{
    		$newArray = array();
	    	$length = strlen($category_id);
	    	
	    	foreach($this->orderedCategories as $category) 
	    	{    		
	    		if($length <= strlen($category->category_id) ) 
	    		{
	    			$prefix = substr($category->category_id, 0, $length);
	    			$sufix = substr($category->category_id, $length);
	    			
	    			if($prefix >= $category_id) {
	    				if($prefix == $category_id) {
	    					$category->delete();
	    				} else {
		    				$prefix = $prefix-1;
		    			
			    			$category->category_id = $prefix . $sufix;
			    			$newArray[$category->category_id] = $category;
			    			$category->update();
	    				}
	    			} else {
	    				$newArray[$category->category_id] = $category;
	    			}
	    		} else {
	    			$newArray[$category->category_id] = $category;
	    		}
	    	}
	    	
	    	$this->orderedCategories = $newArray;
	    	
	    	$this->render();
    	}
    }
    
	public function moveCategoryDown($category_id) 
    {  	
    	$this->swapCategories($category_id, $category_id + 1);
    	$this->render();
    }
    
    public function moveCategoryUp($category_id) 
    {  	
    	$this->swapCategories($category_id, $category_id - 1);
    	$this->render();
    }
    
    private function getCategory($category_id) 
    {
    	if($this->isRootCategory($category_id)) {
    		return $this->orderedCategories[$category_id];
    	} else {
    		$array = $this->childContainerKeyFromChildKey($category_id);
    	}
    }
    
    private function swapCategories($cat1_id, $cat2_id) 
    {
    	if(isset($this->orderedCategories[$cat1_id]) && isset($this->orderedCategories[$cat2_id]))
    	{
	    	$category_length = strlen($cat1_id);
	    	
	    	$newArray = array();

	    	foreach($this->orderedCategories as $category) 
	    	{
	    		if($category_length <= strlen($category->category_id)) {
	    			$prefix = substr($category->category_id, 0, $category_length);
	    			$sufix = substr($category->category_id, $category_length);
	    			
	    			if($prefix == $cat1_id) {
	    				$category->category_id = $cat2_id . $sufix;
	    				$category->update();
	    			} elseif($prefix == $cat2_id) {
	    				$category->category_id = $cat1_id . $sufix;
	    				$category->update();
	    			}
	    		}
	    		$newArray[$category->category_id] = $category;
	    	}
	    	
	    	ksort($newArray);
	    	$this->orderedCategories = $newArray;
    	}
    }
    
    private function updateChildren($array, $prefix) 
    {
    	foreach($array as $key => $value) 
		{
    		$value->category_id = $prefix . substr($value->category_id, -2);
    		$value->update();
    		
    		$this->updateChildren($key, $value->category_id);
		}	
    }
    
	public function render()
	{
		echo '<ol id="categories">';
		foreach ($this->orderedCategories as $key => $category)
		{
			if(!$this->isRootCategory($key)) return;
			
			$this->printListItem($category);
			$this->printAllChildern($category);
			echo '</li>';
		}
		
		if(count($this->orderedCategories) == 0) {
			echo '<div class="category-new" data-id="10">ide rakom</div>';
		}
		
		echo '<li><a class="category-item" data-id="0" data-name="Kategorizálatlan" >Kategorizálatlan</a></li>';
		
		echo '</ol>';
	}
	
	public function renderLeftMenu() 
	{
		echo '<ol id="categories">';
		foreach ($this->orderedCategories as $key => $category)
		{
			if(!$this->isRootCategory($key)) return;
			
			$this->printLeftMenuItem($category);
			$this->printAllChildern($category);
			echo '</li>';
		}
		
		echo '</ol>';
	}
	
	private function printLeftMenuItem($category) 
	{
		$id = $category->category_id;
		$name = $category->name;
		
		$listItem = '<li id="'.$id.'">' . $name;

		echo $listItem;
	}
	
	private function printListItem($category) 
	{
		$id = $category->category_id;
		$name = $category->name;
		$add  = '<div class="category-new" data-id="##ID##">ide rakom</div>';
		$addInside = '<span class="category-new" data-id="##ID##10"> - belerakom</span>';
		$arrows = '<span class="category-arrows" ><a class="up-arrow" onclick="onMoveUpClick('.$id.');"><span class="glyphicon glyphicon-arrow-up"></span></a><a class="down-arrow" onclick="onMoveDownClick('.$id.');"><span class="glyphicon glyphicon-arrow-down "></span></a></span>';
		$trash = '<a class="remove-icon" data-id="##ID##"><span class="glyphicon glyphicon-remove"></span></a>';
		$edit = '<a class="edit-icon" data-id="##ID##" data-name="##NAME##"><span class="glyphicon glyphicon glyphicon-pencil"></span></a>';

		$listItem = $add . '<li id="'.$id.'">'.$arrows.'<a class="category-item" data-id="##ID##" data-name="##NAME##"><span id="category-name_'.$id.'">##NAME##</span></a>' . $trash . $edit . $addInside;
		$listItem = str_replace("##ID##", $id, $listItem);
		$listItem = str_replace("##NAME##", $name, $listItem);
		
		echo $listItem;
	}
	
    private function isRootCategory($id) {
    	if($id < 100) return true;
    	else return false;
    }
    
	private function printRootItemsAndItsChildren($category) 
	{
		$this->printListItem($category);
		$this->printAllChildern($category);
		echo '</li>';
	}
	
	
	private function printAllChildern($category) 
	{
		$children = $this->getChildren($category->category_id);
		
		if(count($children) > 0)
		{
			echo "<ol>";
			foreach($children as $cat) 
			{
				$this->printListItem($cat);
				$this->printAllChildern($cat);
				echo '</li>';
			}
			echo "</ol>";
		}
	}
	
	private function getChildren($id) {
		$res = array();
		foreach($this->orderedCategories as $key => $value)
		{
			if($id == substr($key, 0, -2)) {
				$res[$key] = $value;
			}
		}
		return $res;
	}
	*/
}
?>